#include "mainwindow.h"
#include <QApplication>
#include <QMessageBox>
#include <QDebug>
#include <QElapsedTimer>
#include <QDateTime>
#include <windows.h>
#include <QWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QComboBox>
#include <QSpinBox>
#include <QGroupBox>
#include <QScrollArea>
#include <QStatusBar>
#include <QFrame>
#include <QTimer>
#include <QThread>
#include <QPixmap>
#include <QImage>
#include <QPainter>
#include <QFont>
#include <QQueue>
#include <QMutex>
#include <QWaitCondition>
#include <QSize>
#include <QRect>

// ImageDisplayWidget 实现
ImageDisplayWidget::ImageDisplayWidget(QWidget *parent)
    : QWidget(parent)
{
    setMinimumSize(400, 300);
    setStyleSheet("background-color: white; border: 1px solid #ccc;");
    
    // 创建标签用于显示图像
    m_imageLabel = new QLabel(this);
    m_imageLabel->setAlignment(Qt::AlignCenter);
    m_imageLabel->setText("等待捕获图像...");
    m_imageLabel->setStyleSheet("color: #666; font-size: 14px;");
    
    // 创建滚动区域
    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setWidget(m_imageLabel);
    m_scrollArea->setWidgetResizable(true);
    
    // 设置布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(m_scrollArea);
    setLayout(layout);
}

void ImageDisplayWidget::displayImage(const QImage &image, const QString &qualitySetting)
{
    if (image.isNull()) {
        return;
    }
    
    try {
        // 获取组件尺寸
        int widgetWidth = width();
        int widgetHeight = height();
        
        QImage scaledImage = image;
        
        if (widgetWidth > 1 && widgetHeight > 1) {
            // 计算缩放比例
            int imgWidth = image.width();
            int imgHeight = image.height();
            double scaleX = static_cast<double>(widgetWidth) / imgWidth;
            double scaleY = static_cast<double>(widgetHeight) / imgHeight;
            double scale = qMin(qMin(scaleX, scaleY), 1.0); // 不放大，只缩小
            
            // 简化缩放策略，减少主线程计算负担
            double minScale = 0.3; // 统一使用高性能模式
            if (scale < minScale) {
                scale = minScale;
            }
            
            // 应用缩放（使用快速变换）
            if (scale < 1.0) {
                int newWidth = static_cast<int>(imgWidth * scale);
                int newHeight = static_cast<int>(imgHeight * scale);
                scaledImage = image.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::FastTransformation);
            }
        }
        
        // 创建QPixmap并显示
        m_currentPixmap = QPixmap::fromImage(scaledImage);
        m_imageLabel->setPixmap(m_currentPixmap);
        
        // 清理临时图像数据，释放内存
        scaledImage = QImage();
        
    } catch (const std::exception &e) {
        QMessageBox::critical(this, "错误", QString("显示图像失败: %1").arg(e.what()));
    }
}

// ContinuousCaptureThread 实现
ContinuousCaptureThread::ContinuousCaptureThread(const QString &windowTitle, int fps, bool isFullscreen, bool useWinRT, QObject *parent)
    : QThread(parent)
    , m_windowTitle(windowTitle)
    , m_fps(fps)
    , m_isFullscreen(isFullscreen)
    , m_isRunning(false)
    , m_useWinRT(useWinRT)
    , m_captureItem(nullptr)
    , m_targetFrameInterval(1000000 / fps) // 微秒
    , m_nextOutputTime(0)
    , m_frameCount(0)
    , m_lastFpsTime(0)
    , m_capturedFrames(0)
{
}

ContinuousCaptureThread::~ContinuousCaptureThread()
{
    stopCapture();
    wait(3000); // 等待最多3秒
}

void ContinuousCaptureThread::run()
{
    m_isRunning = true;
    m_nextOutputTime = QDateTime::currentMSecsSinceEpoch() * 1000; // 转换为微秒
    
    // 如果使用WinRT，在子线程中初始化WinRT（MTA）
    if (m_useWinRT) {
        if (!WindowCapture::initializeWinRTForThread()) {
            qDebug() << "子线程WinRT初始化失败，将使用WinAPI捕获";
            m_useWinRT = false;
        }
    }
    
    qDebug() << QString("开始连续捕获 - 目标帧率: %1 FPS, 帧间隔: %2微秒")
                .arg(m_fps).arg(m_targetFrameInterval);
    
    QElapsedTimer captureTimer;
    QElapsedTimer fpsTimer;
    fpsTimer.start();
    
    while (m_isRunning) {
        // 检查是否需要停止
        if (!m_isRunning) break;
        
        // 捕获图像
        captureTimer.start();
        QImage image;
        
        if (m_useWinRT && m_captureItem) {
            // 使用WinRT捕获（在子线程中）
            image = WindowCapture::captureWithItem(m_captureItem);
            
            // 如果WinRT捕获失败，回退到WinAPI
            if (image.isNull()) {
                qDebug() << "WinRT捕获失败，回退到WinAPI";
                if (m_isFullscreen) {
                    HWND desktopHwnd = GetDesktopWindow();
                    image = WindowCapture::captureWindow(desktopHwnd, false);
                } else {
                    HWND hwnd = FindWindowW(nullptr, reinterpret_cast<LPCWSTR>(m_windowTitle.utf16()));
                    if (hwnd) {
                        image = WindowCapture::captureWindow(hwnd, false);
                    }
                }
            }
        } else {
            // 使用WinAPI捕获
            if (m_isFullscreen) {
                HWND desktopHwnd = GetDesktopWindow();
                image = WindowCapture::captureWindow(desktopHwnd, false);
            } else {
                HWND hwnd = FindWindowW(nullptr, reinterpret_cast<LPCWSTR>(m_windowTitle.utf16()));
                if (hwnd) {
                    image = WindowCapture::captureWindow(hwnd, false);
                }
            }
        }
        
        qint64 captureTime = captureTimer.nsecsElapsed() / 1000; // 微秒
        
        if (!image.isNull()) {
            // 记录捕获时间
            m_captureTimes.append(captureTime);
            if (m_captureTimes.size() > MAX_CAPTURE_TIMES) {
                m_captureTimes.removeFirst();
            }
            
            // 直接发送帧数据到主线程，不存储到队列
            // 进一步限制频率，减少主线程负担
            static qint64 lastEmitTime = 0;
            qint64 currentEmitTime = QDateTime::currentMSecsSinceEpoch();
            if (currentEmitTime - lastEmitTime >= 10) {
                emit frameCaptured(image);
                lastEmitTime = currentEmitTime;
            }
            m_capturedFrames++;
            
            // 限制FPS更新频率，避免过度发送信号
            if (fpsTimer.elapsed() >= 1000) { // 每秒更新一次FPS
                float actualFps = static_cast<float>(m_frameCount * 1000.0) / fpsTimer.elapsed();
                emit fpsUpdated(actualFps);
                
                // 每5秒输出一次调试信息
                static qint64 lastDebugTime = 0;
                qint64 currentTime = QDateTime::currentMSecsSinceEpoch() * 1000;
                if (currentTime - lastDebugTime >= 5000000) { // 5秒
                    qint64 avgCaptureTime = 0;
                    if (!m_captureTimes.isEmpty()) {
                        for (qint64 time : m_captureTimes) {
                            avgCaptureTime += time;
                        }
                        avgCaptureTime /= m_captureTimes.size();
                    }
                    
                    qDebug() << QString("性能监控 - 实际FPS: %1, 目标FPS: %2")
                                .arg(actualFps, 0, 'f', 1).arg(m_fps);
                    qDebug() << QString("          - 捕获帧数: %1, 平均捕获时间: %2微秒")
                                .arg(m_capturedFrames).arg(avgCaptureTime / 1000.0, 0, 'f', 1);
                    
                    lastDebugTime = currentTime;
                }
                
                m_frameCount = 0;
                fpsTimer.restart();
            }
            
            m_frameCount++;
        }
        
        // 控制帧率
        qint64 currentTime = QDateTime::currentMSecsSinceEpoch() * 1000;
        qint64 sleepTime = m_nextOutputTime - currentTime;
        
        if (sleepTime > 0) {
            if (sleepTime > 1000) {
                // 大于1ms使用msleep
                msleep(sleepTime / 1000);
            } else {
                // 小于1ms使用yield
                QThread::yieldCurrentThread();
            }
        }
        
        // 更新下一帧时间
        m_nextOutputTime += m_targetFrameInterval;
        
        // 让出CPU时间
        QThread::yieldCurrentThread();
    }
    
    qDebug() << "捕获线程已停止";
}

void ContinuousCaptureThread::stopCapture()
{
    m_isRunning = false;
}

void ContinuousCaptureThread::updateTarget(const QString &windowTitle, bool isFullscreen)
{
    m_windowTitle = windowTitle;
    m_isFullscreen = isFullscreen;
}

void ContinuousCaptureThread::updateFps(int fps)
{
    m_fps = fps;
    m_targetFrameInterval = 1000000 / fps; // 微秒
    qDebug() << QString("帧率已更新为: %1 FPS, 帧间隔: %2微秒").arg(fps).arg(m_targetFrameInterval);
    
    // 重置统计
    m_capturedFrames = 0;
    m_frameCount = 0;
    m_lastFpsTime = QDateTime::currentMSecsSinceEpoch() * 1000;
}

void ContinuousCaptureThread::updateCaptureMethod(bool useWinRT)
{
    m_useWinRT = useWinRT;
    qDebug() << QString("捕获方式已更新为: %1").arg(useWinRT ? "WinRT" : "WinAPI");
}

void ContinuousCaptureThread::setCaptureItem(winrt::Windows::Graphics::Capture::GraphicsCaptureItem item)
{
    m_captureItem = item;
    qDebug() << "CaptureItem已设置";
}

// MainWindow 实现
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_centralWidget(nullptr)
    , m_mainLayout(nullptr)
    , m_windowGroup(nullptr)
    , m_windowCombo(nullptr)
    , m_refreshBtn(nullptr)
    , m_controlGroup(nullptr)
    , m_fpsSpinBox(nullptr)
    , m_qualityCombo(nullptr)
    , m_websocketStatus(nullptr)
    , m_imageGroup(nullptr)
    , m_imageDisplay(nullptr)
    , m_resolutionLabel(nullptr)
    , m_statusLabel(nullptr)
    , m_websocketInfo(nullptr)
    , m_websocketServer(nullptr)
    , m_audioCapture(nullptr)
    , m_applicationManager(nullptr)
    , m_useWinRT(false)
    , m_continuousCaptureThread(nullptr)
    , m_isCapturing(false)
    , m_websocketTimer(nullptr)
    , m_websocketEnabled(false)
    , m_frameProcessTimer(nullptr)
{
    setWindowTitle("窗口捕获工具 - WinAPI版");
    setGeometry(100, 100, 900, 700);
    
    // 初始化WinRT（在主线程中）
    if (WindowCapture::initializeWinRT()) {
        qDebug() << "WinRT初始化成功";
    } else {
        qDebug() << "WinRT初始化失败，将使用WinAPI捕获";
        // 如果WinRT初始化失败，将默认捕获方式改为WinAPI
        m_useWinRT = false;
    }
    
    // 初始化核心功能
    m_websocketServer = new WebSocketServer(this);
    m_audioCapture = new AudioCapture(this);
    m_applicationManager = new ApplicationManager(this);
    
    // 设置UI
    setupUI();
    
    // 初始化
    refreshWindows();
    
    // 启动WebSocket状态更新定时器
    m_websocketTimer = new QTimer(this);
    connect(m_websocketTimer, &QTimer::timeout, this, &MainWindow::onWebSocketStatusUpdated);
    m_websocketTimer->start(1000);
    
    // 初始化帧处理定时器
    m_frameProcessTimer = new QTimer(this);
    connect(m_frameProcessTimer, &QTimer::timeout, this, &MainWindow::processFrameQueue);
    
    // 自动启动WebSocket服务器
    try {
        m_websocketServer->startServer();
        m_websocketEnabled = true;
        
        // 设置初始FPS
        int initialFps = m_fpsSpinBox->value();
        m_websocketServer->setTargetFps(initialFps);
        
        qDebug() << "WebSocket服务器已自动启动 (端口: 8765), 初始FPS:" << initialFps;
    } catch (const std::exception &e) {
        qDebug() << QString("WebSocket服务器启动失败: %1").arg(e.what());
        m_websocketEnabled = false;
    }
    
    // 程序启动时不自动开始捕获，让用户手动控制
    m_statusLabel->setText("就绪 - 请选择窗口并点击开始捕获");
}

MainWindow::~MainWindow()
{
    stopContinuousCapture();
    
    if (m_websocketEnabled) {
        try {
            m_websocketServer->stopServer();
            qDebug() << "WebSocket服务器已停止";
        } catch (const std::exception &e) {
            qDebug() << QString("停止WebSocket服务器时出错: %1").arg(e.what());
        }
    }
}

void MainWindow::setupUI()
{
    m_centralWidget = new QWidget(this);
    setCentralWidget(m_centralWidget);
    
    // 主布局
    m_mainLayout = new QVBoxLayout(m_centralWidget);
    m_mainLayout->setSpacing(10);
    m_mainLayout->setContentsMargins(10, 10, 10, 10);
    
    // 窗口选择区域
    m_windowGroup = new QGroupBox("窗口选择", this);
    QGridLayout *windowLayout = new QGridLayout();
    
    // 捕获方式选择
    windowLayout->addWidget(new QLabel("捕获方式:"), 0, 0);
    m_captureMethodCombo = new QComboBox();
    m_captureMethodCombo->addItems({"WinAPI", "WinRT"});
    // 根据WinRT初始化状态设置默认捕获方式
    if (m_useWinRT) {
        m_captureMethodCombo->setCurrentText("WinRT");
    } else {
        m_captureMethodCombo->setCurrentText("WinAPI");
    }
    connect(m_captureMethodCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &MainWindow::onCaptureMethodChanged);
    windowLayout->addWidget(m_captureMethodCombo, 0, 1);
    
    // 窗口选择
    windowLayout->addWidget(new QLabel("选择窗口:"), 1, 0);
    m_windowCombo = new QComboBox();
    m_windowCombo->setMinimumWidth(400);
    connect(m_windowCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &MainWindow::onWindowSelectionChanged);
    windowLayout->addWidget(m_windowCombo, 1, 1);
    
    // 刷新按钮
    m_refreshBtn = new QPushButton("刷新窗口列表");
    connect(m_refreshBtn, &QPushButton::clicked, this, &MainWindow::refreshWindows);
    windowLayout->addWidget(m_refreshBtn, 1, 2);
    
    m_windowGroup->setLayout(windowLayout);
    m_mainLayout->addWidget(m_windowGroup);
    
    // 捕获控制区域
    m_controlGroup = new QGroupBox("捕获控制", this);
    QGridLayout *controlLayout = new QGridLayout();
    
    // 第一行：帧率设置
    controlLayout->addWidget(new QLabel("捕获帧率:"), 0, 0);
    m_fpsSpinBox = new QSpinBox();
    m_fpsSpinBox->setRange(1, 60);
    m_fpsSpinBox->setValue(30);
    connect(m_fpsSpinBox, QOverload<int>::of(&QSpinBox::valueChanged),
            this, &MainWindow::onFpsChanged);
    controlLayout->addWidget(m_fpsSpinBox, 0, 1);
    controlLayout->addWidget(new QLabel("FPS"), 0, 2);
    
    // 第二行：质量设置
    controlLayout->addWidget(new QLabel("图像质量:"), 1, 0);
    m_qualityCombo = new QComboBox();
    m_qualityCombo->addItems({"最高质量", "高质量", "平衡", "高性能"});
    m_qualityCombo->setCurrentText("平衡");
    connect(m_qualityCombo, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
            this, &MainWindow::onQualityChanged);
    controlLayout->addWidget(m_qualityCombo, 1, 1);
    controlLayout->addWidget(new QLabel("(1080p优先)"), 1, 2);
    
    // 第三行：WebSocket状态显示
    controlLayout->addWidget(new QLabel("WebSocket状态:"), 2, 0);
    m_websocketStatus = new QLabel("运行中");
    m_websocketStatus->setStyleSheet("color: green;");
    controlLayout->addWidget(m_websocketStatus, 2, 1);
    controlLayout->addWidget(new QLabel("(端口: 8765)"), 2, 2);
    
    // 第四行：开始/停止按钮
    m_startStopBtn = new QPushButton("开始捕获");
    m_startStopBtn->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; padding: 8px; }");
    connect(m_startStopBtn, &QPushButton::clicked, this, &MainWindow::toggleCapture);
    controlLayout->addWidget(m_startStopBtn, 3, 0, 1, 3);
    
    m_controlGroup->setLayout(controlLayout);
    m_mainLayout->addWidget(m_controlGroup);
    
    // 图像显示区域
    m_imageGroup = new QGroupBox("捕获预览", this);
    QVBoxLayout *imageLayout = new QVBoxLayout();
    
    m_imageDisplay = new ImageDisplayWidget();
    imageLayout->addWidget(m_imageDisplay);
    
    m_imageGroup->setLayout(imageLayout);
    m_mainLayout->addWidget(m_imageGroup, 1); // 设置拉伸因子为1
    
    // 状态栏
    setupStatusBar();
}

void MainWindow::setupStatusBar()
{
    QStatusBar *statusBar = this->statusBar();
    
    // 分辨率信息
    m_resolutionLabel = new QLabel("分辨率: 未捕获");
    m_resolutionLabel->setFrameStyle(QFrame::StyledPanel);
    statusBar->addWidget(m_resolutionLabel);
    
    // 状态信息
    m_statusLabel = new QLabel("就绪");
    m_statusLabel->setFrameStyle(QFrame::StyledPanel);
    statusBar->addWidget(m_statusLabel);
    
    // WebSocket连接信息
    m_websocketInfo = new QLabel("WebSocket: 0 连接");
    m_websocketInfo->setFrameStyle(QFrame::StyledPanel);
    statusBar->addWidget(m_websocketInfo);
}

void MainWindow::refreshWindows()
{
    try {
        // 使用静态方法获取窗口列表
        QMap<HWND, QString> windowMap = WindowCapture::getAllWindows();
        QStringList windows = windowMap.values();
        
        // 清空并添加选项
        m_windowCombo->clear();
        // 添加"全屏捕获"选项
        m_windowCombo->addItem("全屏捕获");
        // 添加所有窗口
        m_windowCombo->addItems(windows);
        
        // 默认选择"全屏捕获"
        m_windowCombo->setCurrentIndex(0);
        m_statusLabel->setText(QString("找到 %1 个窗口，已添加全屏捕获选项").arg(windows.size()));
    } catch (const std::exception &e) {
        QMessageBox::critical(this, "错误", QString("获取窗口列表失败: %1").arg(e.what()));
        m_statusLabel->setText("获取窗口列表失败");
    }
}

void MainWindow::toggleCapture()
{
    if (m_isCapturing) {
        // 停止捕获
        stopContinuousCapture();
        m_startStopBtn->setText("开始捕获");
        m_startStopBtn->setStyleSheet("QPushButton { background-color: #4CAF50; color: white; font-weight: bold; padding: 8px; }");
    } else {
        // 开始捕获
        QString windowTitle = m_windowCombo->currentText();
        bool isFullscreen = (windowTitle == "全屏捕获");
        
        if (isFullscreen) {
            startContinuousCapture("", true);
        } else {
            startContinuousCapture(windowTitle, false);
        }
        
        m_startStopBtn->setText("停止捕获");
        m_startStopBtn->setStyleSheet("QPushButton { background-color: #f44336; color: white; font-weight: bold; padding: 8px; }");
    }
}

void MainWindow::onWindowSelectionChanged(const QString &windowTitle)
{
    if (windowTitle.isEmpty()) {
        return;
    }
    
    // 检查是否为全屏捕获
    if (windowTitle == "全屏捕获") {
        m_statusLabel->setText("切换到全屏捕获模式");
        // 更新连续捕获的目标为全屏
        if (m_continuousCaptureThread && m_continuousCaptureThread->isRunning()) {
            m_continuousCaptureThread->updateTarget("", true);
        } else {
            // 如果没有运行连续捕获，启动全屏捕获
            startContinuousCapture("", true);
        }
    } else {
        m_statusLabel->setText(QString("切换到窗口: %1").arg(windowTitle));
        // 更新连续捕获的目标为指定窗口
        if (m_continuousCaptureThread && m_continuousCaptureThread->isRunning()) {
            m_continuousCaptureThread->updateTarget(windowTitle, false);
        } else {
            // 如果没有运行连续捕获，启动窗口捕获
            startContinuousCapture(windowTitle, false);
        }
    }
}

void MainWindow::onQualityChanged(const QString &quality)
{
    if (!m_capturedImage.isNull()) {
        displayImage(m_capturedImage);
        m_statusLabel->setText(QString("图像质量已更新为: %1").arg(quality));
    }
}

void MainWindow::onCaptureMethodChanged()
{
    QString method = m_captureMethodCombo->currentText();
    m_useWinRT = (method == "WinRT");
    
    // 更新窗口标题
    if (m_useWinRT) {
        setWindowTitle("窗口捕获工具 - WinRT版");
    } else {
        setWindowTitle("窗口捕获工具 - WinAPI版");
    }
    
    m_statusLabel->setText(QString("捕获方式已切换为: %1").arg(method));
    
    // 如果正在捕获，更新线程的捕获方式
    if (m_isCapturing && m_continuousCaptureThread) {
        m_continuousCaptureThread->updateCaptureMethod(m_useWinRT);
    }
}

void MainWindow::onFpsChanged(int fps)
{
    if (m_continuousCaptureThread && m_continuousCaptureThread->isRunning()) {
        m_continuousCaptureThread->updateFps(fps);
        m_statusLabel->setText(QString("帧率已更新为: %1 FPS").arg(fps));
    }
    
    // 更新WebSocket服务器的帧率设置
    if (m_websocketServer) {
        m_websocketServer->setTargetFps(fps);
    }
    
    // 更新帧处理定时器间隔
    if (m_frameProcessTimer) {
        int intervalMs = 1000 / fps; // 转换为毫秒
        m_frameProcessTimer->setInterval(intervalMs);
        qDebug() << "帧处理定时器间隔设置为:" << intervalMs << "ms (FPS:" << fps << ")";
    }
}

void MainWindow::startContinuousCapture(const QString &windowTitle, bool isFullscreen)
{
    if (m_isCapturing) {
        return;
    }
    
    // 停止之前的捕获线程
    if (m_continuousCaptureThread && m_continuousCaptureThread->isRunning()) {
        m_continuousCaptureThread->stopCapture();
        m_continuousCaptureThread->wait();
    }
    
    // 确定捕获目标
    QString targetTitle = windowTitle;
    bool targetFullscreen = isFullscreen;
    
    if (targetTitle.isEmpty() && !isFullscreen) {
        targetTitle = m_windowCombo->currentText();
        if (targetTitle == "全屏捕获") {
            targetFullscreen = true;
            targetTitle = "";
        }
    }
    
    // 创建并启动连续捕获线程
    int fps = m_fpsSpinBox->value();
    m_continuousCaptureThread = new ContinuousCaptureThread(targetTitle, fps, targetFullscreen, m_useWinRT, this);
    
    // 如果使用WinRT，在主线程中创建GraphicsCaptureItem
    if (m_useWinRT) {
        HWND hwnd = nullptr;
        if (targetFullscreen) {
            hwnd = GetDesktopWindow();
        } else {
            hwnd = FindWindowW(nullptr, reinterpret_cast<LPCWSTR>(targetTitle.utf16()));
        }
        
        if (hwnd) {
            auto captureItem = WindowCapture::createCaptureItemForWindow(hwnd);
            if (captureItem) {
                m_continuousCaptureThread->setCaptureItem(captureItem);
                qDebug() << "GraphicsCaptureItem已创建并传递给捕获线程";
            } else {
                qDebug() << "无法创建GraphicsCaptureItem，将使用WinAPI捕获";
                m_continuousCaptureThread->updateCaptureMethod(false);
            }
        } else {
            qDebug() << "无法找到目标窗口，将使用WinAPI捕获";
            m_continuousCaptureThread->updateCaptureMethod(false);
        }
    }
    
    // 连接信号和槽
    connect(m_continuousCaptureThread, &ContinuousCaptureThread::frameCaptured,
            this, &MainWindow::onFrameCaptured, Qt::QueuedConnection);
    connect(m_continuousCaptureThread, &ContinuousCaptureThread::fpsUpdated,
            this, &MainWindow::onFpsUpdated, Qt::QueuedConnection);
    
    // 设置线程优先级
    m_continuousCaptureThread->setPriority(QThread::NormalPriority);
    
    // 启动线程
    m_continuousCaptureThread->start();
    
    // 启动帧处理定时器
    if (m_frameProcessTimer) {
        int fps = m_fpsSpinBox->value();
        int intervalMs = 1000 / fps;
        m_frameProcessTimer->setInterval(intervalMs);
        m_frameProcessTimer->start();
        qDebug() << "帧处理定时器已启动，间隔:" << intervalMs << "ms";
    }
    
    m_isCapturing = true;
    if (targetFullscreen) {
        m_statusLabel->setText("连续捕获已启动 - 全屏模式");
    } else {
        m_statusLabel->setText(QString("连续捕获已启动 - 窗口: %1").arg(targetTitle));
    }
    
    qDebug() << "捕获线程已启动";
}

void MainWindow::stopContinuousCapture()
{
    if (m_continuousCaptureThread && m_continuousCaptureThread->isRunning()) {
        qDebug() << "正在停止捕获线程...";
        m_continuousCaptureThread->stopCapture();
        
        // 等待线程结束，最多等待3秒
        if (!m_continuousCaptureThread->wait(3000)) {
            qWarning() << "捕获线程未在3秒内结束，强制终止...";
            m_continuousCaptureThread->terminate();
            m_continuousCaptureThread->wait(1000);
        }
        
        // 断开信号连接
        disconnect(m_continuousCaptureThread, nullptr, this, nullptr);
        
        // 删除线程对象
        m_continuousCaptureThread->deleteLater();
        m_continuousCaptureThread = nullptr;
    }
    
    // 停止帧处理定时器
    if (m_frameProcessTimer) {
        m_frameProcessTimer->stop();
        qDebug() << "帧处理定时器已停止";
    }
    
    // 清空帧队列
    {
        QMutexLocker locker(&m_frameQueueMutex);
        m_frameQueue.clear();
    }
    
    m_isCapturing = false;
    m_statusLabel->setText("连续捕获已停止");
    qDebug() << "捕获线程已停止";
}

void MainWindow::onFrameCaptured(const QImage &image)
{
    // 检查图像是否有效
    if (image.isNull()) {
        return;
    }
    
    // 将帧添加到队列中
    addFrameToQueue(image);
}

void MainWindow::onFpsUpdated(float fps)
{
    if (fps > 0) {
        m_statusLabel->setText(QString("连续捕获中 - 实时帧率: %1 FPS").arg(fps, 0, 'f', 1));
    }
}

void MainWindow::onWebSocketStatusUpdated()
{
    updateWebSocketStatus();
}

void MainWindow::updateResolutionDisplay(const QImage &image)
{
    if (!image.isNull()) {
        int width = image.width();
        int height = image.height();
        
        // 判断分辨率等级
        QString quality;
        if (width >= 1920 && height >= 1080) {
            quality = "1080p+ (高清)";
        } else if (width >= 1280 && height >= 720) {
            quality = "720p (标清)";
        } else if (width >= 800 && height >= 600) {
            quality = "VGA+";
        } else {
            quality = "低分辨率";
        }
        
        m_resolutionLabel->setText(QString("分辨率: %1×%2 - %3").arg(width).arg(height).arg(quality));
    } else {
        m_resolutionLabel->setText("分辨率: 未捕获");
    }
}

void MainWindow::displayImage(const QImage &image)
{
    m_capturedImage = image.copy();
    
    QString quality = m_qualityCombo->currentText();
    m_imageDisplay->displayImage(image, quality);
}

void MainWindow::updateWebSocketStatus()
{
    if (m_websocketEnabled && m_websocketServer->isServerRunning()) {
        int clientCount = m_websocketServer->getClientCount();
        m_websocketInfo->setText(QString("WebSocket: %1 连接").arg(clientCount));
        // 更新状态标签
        if (clientCount > 0) {
            m_websocketStatus->setText(QString("运行中 (%1 连接)").arg(clientCount));
            m_websocketStatus->setStyleSheet("color: green;");
        } else {
            m_websocketStatus->setText("运行中 (等待连接)");
            m_websocketStatus->setStyleSheet("color: green;");
        }
    } else {
        m_websocketInfo->setText("WebSocket: 启动失败");
        m_websocketStatus->setText("启动失败");
        m_websocketStatus->setStyleSheet("color: red;");
    }
}

void MainWindow::addFrameToQueue(const QImage &image)
{
    QMutexLocker locker(&m_frameQueueMutex);
    
    // 如果队列已满，移除最旧的帧
    if (m_frameQueue.size() >= MAX_FRAME_QUEUE_SIZE) {
        m_frameQueue.dequeue();
    }
    
    // 添加新帧到队列
    m_frameQueue.enqueue(image);
    
    // 输出队列状态（每100帧输出一次）
    static int frameCount = 0;
    if (++frameCount % 100 == 0) {
        qDebug() << "帧队列状态: 当前大小" << m_frameQueue.size() << "/" << MAX_FRAME_QUEUE_SIZE;
    }
}

void MainWindow::processFrameQueue()
{
    QMutexLocker locker(&m_frameQueueMutex);
    
    // 如果队列为空，直接返回
    if (m_frameQueue.isEmpty()) {
        return;
    }
    
    // 从队列中取出最新的一帧
    QImage image = m_frameQueue.dequeue();
    locker.unlock(); // 释放锁，避免在后续处理中持有锁
    
    // 检查图像是否有效
    if (image.isNull()) {
        return;
    }
    
    try {
        // 限制图像大小，避免内存占用过大（使用快速变换）
        QImage scaledImage = image;
        // if (image.width() > 1920 || image.height() > 1080) {
        //     scaledImage = image.scaled(1920, 1080, Qt::KeepAspectRatio, Qt::FastTransformation);
        // }
        
        // 显示图像
        displayImage(scaledImage);
        
        // 减少分辨率更新频率，避免过度更新UI
        static int resolutionUpdateCounter = 0;
        if (++resolutionUpdateCounter % 5 == 0) {
            updateResolutionDisplay(scaledImage);
        }
        
        // 通过WebSocket广播帧（使用原始图像）
        // 使用异步版本避免阻塞主线程
        if (m_websocketEnabled && m_websocketServer) {
            m_websocketServer->broadcastFrameAsync(image);
        }
        
        // 输出处理统计（每50帧输出一次）
        static int processedCount = 0;
        if (++processedCount % 50 == 0) {
            int queueSize = 0;
            {
                QMutexLocker tempLocker(&m_frameQueueMutex);
                queueSize = m_frameQueue.size();
            }
            qDebug() << "帧处理统计: 已处理" << processedCount << "帧, 队列剩余" << queueSize << "帧";
        }
        
    } catch (const std::exception &e) {
        qDebug() << "processFrameQueue处理异常:" << e.what();
    }
}
